<?php

function pwGen($password,$md5ed=False) 
{
	if (!$md5ed) $password=md5($password);
	$salt = sha1(rand());
	$salt = substr($salt, 0, 4);
	$hash = base64_encode( sha1($password . $salt, true) . $salt ); 
	return $hash; 
}

function pwCheck($password,$saved)
{

	if (isOldPW($saved)){
		$mpw = md5($password);
		if ($mpw==$saved) return True;
		else return False;
	}
	$svd=base64_decode($saved);
	$salt=substr($svd,20);
	$hash = base64_encode( sha1(md5($password) . $salt, true) . $salt );
	if (strcmp($hash,$saved)==0) return True;
	else return False;
}

function isOldPW($password)
{
	for ($i=strlen($password)-1;$i>=0;$i--)
	{
		$c = $password[$i];
		if ('0'<=$c && $c<='9') continue;
		if ('a'<=$c && $c<='f') continue;
		if ('A'<=$c && $c<='F') continue;
		return False;
	}
	return True;
}

function is_valid_user_name($user_name){
	$len=strlen($user_name);
	for ($i=0;$i<$len;$i++){
		if (
			($user_name[$i]>='a' && $user_name[$i]<='z') ||
			($user_name[$i]>='A' && $user_name[$i]<='Z') ||
			($user_name[$i]>='0' && $user_name[$i]<='9') ||
			$user_name[$i]=='_'||
			($i==0 && $user_name[$i]=='*') 
		);
		else return false;
	}
	return true;
}

function sec2str($sec){
	return sprintf("%02d:%02d:%02d",$sec/3600,$sec%3600/60,$sec%60);
}

/**
 * @param $time
 * @return bool|int|string
 * �ʼ�ʱ����ʾ
 */
function timeExchange($time){
	$time = !is_numeric($time) ? strtotime($time):$time;
	$now = time();

	$diff = $now - $time;
	$today_lingdian = strtotime(date('Y-m-d')." 00:00:00");
	$yesterday_lingdian = strtotime(date('Y-m-d',strtotime('yesterday'))." 00:00:00");

	if($diff <= 60){
		return ($diff%60)." seconds ago";
	}else if($diff<=3600 && $diff > 60){
		return intval($diff/60)." minutes ago";
	}else if($diff<=86400 && $diff > 3600){
		if($today_lingdian > $time){
			return "Yesterday".date('H:i',$time);
		}
		return "today ".date('H:i',$time);
	}else if($time>=strtotime(date('Y-')."01-01") && $diff>86400){
		if($yesterday_lingdian > $time){
			return date('m-d H:i',$time);
		}
		return "Yesterday ".date('H:i',$time);
	}else {
		return date('Y-m-d H:i',$time);
	}
//	return $time_str;
}

function set_param_key($type='post'){

	$str = MD5($_SESSION['USER']['user_id'].rand(0,9999999));
	$str = substr($str,0,10);
	$str = strtoupper($str);

	if('post'==$type)
		$_SESSION['postkey'] = $str;
	$_SESSION['gettkey'] = $str;
}
function check_param_key($val,$type='post'){

	$session = ('post'==$type) ? $_SESSION['postkey'] : $_SESSION['gettkey'];

	if (!isset($session)||!isset($val)||$session!=$val)
		return false;
	return true;
}

